import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Session,
  Res,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import type { Response, Express } from 'express';
import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
import { zip } from 'compressing';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  findAll() {
    return 'userInfo: 哈哈哈';
  }

  @Get('code')
  getCode(@Res() res, @Session() session) {
    const code = this.userService.getCode();
    session.code = code.text;
    res.type('image/svg+xml');
    res.send(code.data);
  }

  @Post('create')
  createUser(@Body() body, @Session() session) {
    if (session.code.toLocaleLowerCase() === body.code.toLocaleLowerCase()) {
      return {
        code: 200,
        data: null,
        msg: 'success',
      };
    } else {
      return {
        code: 400,
        data: null,
        msg: '验证码错误',
      };
    }
  }
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file: Express.Multer.File) {
    return {
      code: 0,
      data: file,
      msg: 'success',
    };
  }
  @Get('export/:ext')
  downLoad(@Res() res: Response, @Param() param) {
    const url = join(__dirname, '../images/' + param.ext);
    res.download(url);
  }
  @Get('stream/:ext')
  async getStream(@Res() res: Response, @Param() param) {
    const url = join(__dirname, '../images/' + param.ext);
    const stream = new zip.Stream();
    await stream.addEntry(url);
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', 'attachment; filename=ss');
    stream.pipe(res);
    // 前端实现
    // fetch(url)
    //   .then((res) => res.blob())
    //   .then((res) => {
    //     console.log('res', res);
    //     const resUrl = URL.createObjectURL(res);
    //     const a = document.createElement('a');
    //     a.href = resUrl;
    //     a.download = 'sss.zip';
    //     a.click();
    //   });
  }
}
